/*
 *    Copyright 2009-2021 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.reflection.wrapper;

import org.apache.ibatis.reflection.*;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.invoker.Invoker;
import org.apache.ibatis.reflection.property.PropertyTokenizer;

import java.util.List;

/** @author Clinton Begin */
public class BeanWrapper extends BaseWrapper {

  private final Object object;
  private final MetaClass metaClass;

  public BeanWrapper(MetaObject metaObject, Object object) {
    super(metaObject);
    this.object = object;
    this.metaClass = MetaClass.forClass(object.getClass(), metaObject.getReflectorFactory());
  }

  /**
   * 获取对象
   *
   * @param prop PropertyTokenizer 分词器
   * @return 目标对象
   */
  @Override
  public Object get(PropertyTokenizer prop) {
    // 判断索引是否为空
    if (prop.getIndex() != null) {
      // 返回对象集合
      Object collection = resolveCollection(prop, object);
      // 返回对象集合中指定的对象
      return getCollectionValue(prop, collection);
    } else {
      return getBeanProperty(prop, object);
    }
  }

  /**
   * 设置对象
   *
   * @param prop PropertyTokenizer 分词器
   * @param value 对象
   */
  @Override
  public void set(PropertyTokenizer prop, Object value) {
    if (prop.getIndex() != null) {
      // 获取集合中的对象
      Object collection = resolveCollection(prop, object);
      // 设置对象的值
      setCollectionValue(prop, collection, value);
    } else {
      // 直接设置对象的值
      setBeanProperty(prop, object, value);
    }
  }

  @Override
  public String findProperty(String name, boolean useCamelCaseMapping) {
    return metaClass.findProperty(name, useCamelCaseMapping);
  }

  @Override
  public String[] getGetterNames() {
    return metaClass.getGetterNames();
  }

  @Override
  public String[] getSetterNames() {
    return metaClass.getSetterNames();
  }

  /**
   * 获取设置对象的类型
   *
   * @param name
   * @return
   */
  @Override
  public Class<?> getSetterType(String name) {
    PropertyTokenizer prop = new PropertyTokenizer(name);
    // 如果有 children 表达式
    if (prop.hasNext()) {
      MetaObject metaValue = metaObject.metaObjectForProperty(prop.getIndexedName());
      // 如果为 空对象的 MetaObject 对象
      if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
        // 调用 MetaClass#getSetterType 方法获取属性名对应的属性类型
        return metaClass.getSetterType(name);
      } else {
        // 如果 MetaObject 对象不是空对象
        // 继续遍历
        return metaValue.getSetterType(prop.getChildren());
      }
    } else {
      // 没有 children 表达式，直接调用 MetaClass#getSetterType 获取对应的类型类
      return metaClass.getSetterType(name);
    }
  }

  /**
   * 获取 getter 方法类型
   *
   * @param name name 表达式
   * @return 类型
   */
  @Override
  public Class<?> getGetterType(String name) {
    PropertyTokenizer prop = new PropertyTokenizer(name);
    if (prop.hasNext()) {
      MetaObject metaValue = metaObject.metaObjectForProperty(prop.getIndexedName());
      if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
        return metaClass.getGetterType(name);
      } else {
        return metaValue.getGetterType(prop.getChildren());
      }
    } else {
      return metaClass.getGetterType(name);
    }
  }

  @Override
  public boolean hasSetter(String name) {
    PropertyTokenizer prop = new PropertyTokenizer(name);
    if (prop.hasNext()) {
      // 调用 MetaClass#hasSetter 判断是否存在 setter 方法
      if (metaClass.hasSetter(prop.getIndexedName())) {
        MetaObject metaValue = metaObject.metaObjectForProperty(prop.getIndexedName());
        if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
          return metaClass.hasSetter(name);
        } else {
          return metaValue.hasSetter(prop.getChildren());
        }
      } else {
        return false;
      }
    } else {
      return metaClass.hasSetter(name);
    }
  }

  @Override
  public boolean hasGetter(String name) {
    PropertyTokenizer prop = new PropertyTokenizer(name);
    if (prop.hasNext()) {
      if (metaClass.hasGetter(prop.getIndexedName())) {
        MetaObject metaValue = metaObject.metaObjectForProperty(prop.getIndexedName());
        if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
          return metaClass.hasGetter(name);
        } else {
          return metaValue.hasGetter(prop.getChildren());
        }
      } else {
        return false;
      }
    } else {
      return metaClass.hasGetter(name);
    }
  }

  /**
   * 实例化属性值
   *
   * @param name 属性名
   * @param prop PropertyTokenizer 分词器
   * @param objectFactory 对象工厂
   * @return MetaObject 对象
   */
  @Override
  public MetaObject instantiatePropertyValue(
      String name, PropertyTokenizer prop, ObjectFactory objectFactory) {
    MetaObject metaValue;
    // 获取属性类型，实际上是调用 MetaClass#getSetterType()
    Class<?> type = getSetterType(prop.getName());
    try {
      Object newObject = objectFactory.create(type);
      // 获取 metaValue 对象
      metaValue =
          MetaObject.forObject(
              newObject,
              metaObject.getObjectFactory(),
              metaObject.getObjectWrapperFactory(),
              metaObject.getReflectorFactory());
      // 设置目标对象的值
      set(prop, newObject);
    } catch (Exception e) {
      throw new ReflectionException(
          "Cannot set value of property '"
              + name
              + "' because '"
              + name
              + "' is null and cannot be instantiated on instance of "
              + type.getName()
              + ". Cause:"
              + e.toString(),
          e);
    }
    return metaValue;
  }

  /**
   * 通过类属性返回对象
   *
   * @param prop PropertyTokenizer 分词器
   * @param object 目标对象
   * @return 指定对象
   */
  private Object getBeanProperty(PropertyTokenizer prop, Object object) {
    try {
      // 获取 类的 Getter 方法
      Invoker method = metaClass.getGetInvoker(prop.getName());
      try {
        // 调用 Getter 方法返回对象
        return method.invoke(object, NO_ARGUMENTS);
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (Throwable t) {
      throw new ReflectionException(
          "Could not get property '"
              + prop.getName()
              + "' from "
              + object.getClass()
              + ".  Cause: "
              + t.toString(),
          t);
    }
  }

  /**
   * 设置对象属性
   *
   * @param prop PropertyTokenizer 分词器
   * @param object 对象
   * @param value 对象值
   */
  private void setBeanProperty(PropertyTokenizer prop, Object object, Object value) {
    try {
      // 获取 setter 方法
      Invoker method = metaClass.getSetInvoker(prop.getName());
      // setter 方法参数
      Object[] params = {value};
      try {
        // 调用 setter 方法
        method.invoke(object, params);
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    } catch (Throwable t) {
      throw new ReflectionException(
          "Could not set property '"
              + prop.getName()
              + "' of '"
              + object.getClass()
              + "' with value '"
              + value
              + "' Cause: "
              + t.toString(),
          t);
    }
  }

  @Override
  public boolean isCollection() {
    return false;
  }

  @Override
  public void add(Object element) {
    throw new UnsupportedOperationException();
  }

  @Override
  public <E> void addAll(List<E> list) {
    throw new UnsupportedOperationException();
  }
}
